<?php

namespace addons\tools\model;

use think\Model;

class Meal extends Model
{
    protected $name = 'user_meal';
    protected $append = [
        'ageing',
        'type_text',
    ];
    protected $days = [
        'day'   => '天',
        'month' => '月',
        'year'  => '年'
    ];

    public function getTypeTextAttr($value, $data)
    {
        return $this->days[$data['type']];
    }

    public function getAgeingAttr($name, $data)
    {
        $str = 0;
        if ($data['days'] > 0) {
            $str = $data['days'] . '天';
        }
        if ($data['days'] >= 30 && $data['days'] <= 365) {
            $str = ceil($data['days'] / 30) . '月';
        }

        if ($data['days'] >= 365) {
            $str = ceil($data['days'] / 365) . '年';
        }
        return $str;

    }

    public function getIconAttr($value)
    {
        return $value ? cdnurl($value, false, true) : $value;
    }

    public function getLists()
    {
        return $this->field('id,type,name,desc,days,price,original_price,icon')
            ->with(['rules' => function ($query) {
                $query->alias('a')->field('a.meal_id,a.number,b.name as tool_name')->join('tools b', 'b.id=a.tool_id', 'left');
            }])
            ->where('status', 'normal')->order('weigh', 'DESC')->select();
    }

    public function getDetail($id)
    {
        return $this->where('status', 'normal')->with(['rules' => function ($query) {
            $query->alias('a')->field('a.meal_id,a.number,b.name as tool_name')->join('tools b', 'b.id=a.tool_id', 'left');
        }])->find($id);
    }

    public function rules()
    {
        return $this->hasMany(MealRule::class, 'meal_id', 'id');
    }

}